package com.cloud.wyf.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.cloud.wyf.Entity.*;
import com.cloud.wyf.Entity.Dto.LeaderShipDto;
import com.cloud.wyf.Entity.Dto.MiddelDto;
import com.cloud.wyf.Service.UserService;
import com.cloud.wyf.Util.OutUtil;
import com.cloud.wyf.Util.PdfUtil;
import org.apache.commons.io.IOUtils;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService us;

    @Autowired
    private DocumentConverter converter;

    /**
     * 导出教职工登录账号
     * @param response
     * @return
     */
    @GetMapping("/outport")
    public void outPort(HttpServletResponse response) throws InterruptedException {
        int total = us.totalNum();
        List<Part> parts = us.selectAllPart();
        List<User> users = new ArrayList<>();
        List<Ordinary> ordinaries = new ArrayList<>();
        String password = new BCryptPasswordEncoder().encode("123456");
        User userTemplate = new User();
        userTemplate.setRealname("教职工");
        userTemplate.setPassword(password);
        userTemplate.setRole(3);
        userTemplate.setStatus(0);
        int num = 0;
        int num1 = 2;
        int partNum = 0;
        List<Ordinary> ordinarie = us.selectAllOrdinary();
        if (ordinarie.size() == total) {//判断数据库中是否有test数据，有则直接拿，没有重新生成
            List<String> ids = ordinarie.stream().map((item) -> {
                return item.getUid();
            }).collect(Collectors.toList());
            List<User> users1 = us.MultiSelect(ids);
           // us.outport(users1, ordinarie);
            OutUtil.exportExcel(response, users1);
        } else{
            for (int j = 0; j < parts.size(); j++) {
                partNum = parts.get(j).getNum();
                num += partNum;
                for (int i = num1; i < num + 2; i++) {
                    User user1 = new User(userTemplate);
                    user1.setId(String.valueOf(i));
                    user1.setNickname("pt" + String.valueOf(i));
                    user1.setPart(parts.get(j).getPart()); // 使用当前Part对象的值
                    users.add(user1);
                }
                num1 += partNum; // 更新num1为当前Part对象的num
            }
        // executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
        new Thread(() -> {
            users.stream().forEach(user -> {//利用stream流并行创建
                ordinaries.add(new Ordinary(user.getId(), "教职工", user.getPart(), 0, 0));
            });
//            us.MultiUser(users);
//            us.MultiAddOr(ordinaries);
            us.outport(users, ordinaries);
        }).start();
        OutUtil.exportExcel(response, users);
    }

    }

    @GetMapping
    public String getLeaders(@RequestParam("uids") String uids,HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        String[] s = JSONObject.parseObject(uids, String[].class);
        List<String> list=new ArrayList<>();
        for(int i=0;i<s.length;i++){
            list.add(s[i]);
        }
        return JSONObject.toJSONString(us.selectLeaderByUids(list));
    }

    @RequestMapping("/getUser")
    public String getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("user");
      //  System.out.println(GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token")));
        if(user!=null) return JSONObject.toJSONString(Message.success(user));
        else return JSONObject.toJSONString(Message.failure("user info fade"));
    }

    /**
     * 更改中层干部所属部分，职务信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/update")
    public String updateMiddel(HttpServletRequest request,HttpServletResponse response){
        List<Middel> list=new ArrayList<>(1);
        String uid = request.getParameter("uid");
        String part = request.getParameter("part");
        String position = request.getParameter("position");
        if(part==null||"".equals(part)||position==null||"".equals(position)) JSONObject.toJSONString(Message.failure("data is not complete."));
        Middel middel=new Middel();
        middel.setUid(uid);
        middel.setPart(part);
        middel.setPosition(position);
        middel.setLevel(position);
        list.add(middel);
        int i = us.updateInfo(list);
        if(i>0) return JSONObject.toJSONString(Message.success("success update"));
        else return JSONObject.toJSONString(Message.failure("failure update"));
    }

    @RequestMapping("/getData")
    public String getData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        List<Middel> list = us.selectAllMi();
        List<MiddelDto> list1=new ArrayList<>();
        for(Middel middel:list){
            if(middel.getStatus()==1){
                list1.add(new MiddelDto(middel.getUid(),middel.getRealname(),middel.getPart(),middel.getPosition(),middel.getLevel(),"已上传",middel.getSummarypath(),middel.getSummarytime(),middel.getStatus()));
            }else list1.add(new MiddelDto(middel.getUid(),middel.getRealname(),middel.getPart(),middel.getPosition(),middel.getLevel(),"未上传",middel.getSummarypath(),middel.getSummarytime(),middel.getStatus()));
        }
        return JSONObject.toJSONString(Message.success(list1));
    }

    /**
     * 得到中层干部分页查询
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/getPage")
    public String getPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        Integer currentPage = Integer.valueOf(request.getParameter("currentPage"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        PageBean<MiddelDto> middelPageBean = us.selectByPage(currentPage, pageSize);
        return JSONObject.toJSONString(Message.success(middelPageBean));
    }

    /**
     * 得到领导班子的分页查询
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/getPageL")
    public String getPageL(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        Integer currentPage = Integer.valueOf(request.getParameter("currentPage"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        PageBean<LeaderShipDto> middelPageBean = us.selectByPageL(currentPage, pageSize);
        return JSONObject.toJSONString(Message.success(middelPageBean));
    }

    @RequestMapping("/byMiddel")
    public Message data(HttpServletRequest request, HttpServletResponse response){
        String uid = request.getParameter("uid");
        System.out.println(uid);
        Middel middel = us.selectMidById(uid);
        if(middel!=null)
        return Message.success(middel);
        else return Message.failure("not exist");
    }


    @RequestMapping("/byLeaderShip")
    public Message byLeaderShip(HttpServletRequest request, HttpServletResponse response){
        String uid = request.getParameter("uid");
        User user = us.selectUserById(uid);
        LeaderShip leaderShip = us.selectLeaderShipByPart(user.getPart());
        if(leaderShip!=null)
            return Message.success(leaderShip);
        else return Message.failure("not exist");
    }

    /**
     * 预览述职报告
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/look")
    public Message look(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf;charset=UTF-8");
        String uid = request.getParameter("uid");
        Middel middel = us.selectMidById(uid);
        File file=new File("E:\\testMyDoc\\"+"JCccc" + uid+".pdf");
        if(file.exists()){
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(file);// 读取文件
            int i = IOUtils.copy(in, outputStream);   // copy流数据,i为字节数
            in.close();
            outputStream.close();
            return null;
        }
        if(middel.getStatus()!=0) {
            PdfUtil pdfUtil = new PdfUtil(converter);
            pdfUtil.tern(response, middel.getSummarypath(), uid);
            return null;
        }
        return Message.failure("This middel not upload report");
    }

    /**
     * 预览领导班子报告
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/lookL")
    public Message lookL(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf;charset=UTF-8");
        String uid = request.getParameter("uid");
        String part = us.selectUserById(uid).getPart();
        LeaderShip leaderShip = us.selectLeaderShipByPart(part);
            File file = new File("E:\\testMyDoc\\" + "JCccc" + leaderShip.getPart() + ".pdf");
            if (file.exists()) {
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream in = new FileInputStream(file);// 读取文件
                int i = IOUtils.copy(in, outputStream);   // copy流数据,i为字节数
                in.close();
                outputStream.close();
                return null;
            }
            if (leaderShip.getStatus() != 0) {
                PdfUtil pdfUtil = new PdfUtil(converter);
                pdfUtil.ternL(response, leaderShip.getReportpath(), leaderShip.getPart());
                return null;
            }
        return Message.failure("This  not upload report");
    }

    @RequestMapping("/checksuccess")
    public Message checksuccess(HttpServletRequest request,HttpServletResponse response){
        String uid = request.getParameter("uid");
        int i = us.updateStatus(1, uid);
        if(i>0) return Message.success("success");
        return Message.failure("failure");
    }

    @RequestMapping("/checkfailure")
    public Message checkfailure(HttpServletRequest request,HttpServletResponse response){
        String uid = request.getParameter("uid");
        int i = us.updateStatus(3, uid);
        if(i>0) return Message.success("success");
        return Message.failure("failure");
    }

    @RequestMapping("/checksuccess1")
    public Message checksuccess1(HttpServletRequest request,HttpServletResponse response){
        String uid = request.getParameter("uid");
        int i = us.updateLeaderShipStatus(1, us.selectUserById(uid).getPart());
        if(i>0) return Message.success("success");
        return Message.failure("failure");
    }

    @RequestMapping("/checkfailure1")
    public Message checkfailure1(HttpServletRequest request,HttpServletResponse response){
        String uid = request.getParameter("uid");
        int i = us.updateLeaderShipStatus(3, us.selectUserById(uid).getPart());
        if(i>0) return Message.success("success");
        return Message.failure("failure");
    }
}
